package com.colorlight.cloud.mqtt.base.core.pool;

import com.colorlight.cloud.mqtt.base.core.properties.MqttProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @author Demon
 * 自定义线程池配置类
 */
@Configuration
public class ThreadPool {
	private final MqttProperties properties;
	/**
	 * 订阅事件推送
	 */
	private static final String THREAD_PREFIX_NAME_EVENT_DELIVER = "subscription-event-deliver-";
	
	public ThreadPool(MqttProperties properties) {
		this.properties = properties;
	}
	
	@Bean
	public ThreadPoolTaskExecutor subscriptionEventDeliverTaskExecutor() {
		ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
		//事件发送不怎么占用cpu资源但是有可能重试时会占用线程, 所以线程数越多,推送事件越快/多
		threadPoolTaskExecutor.setCorePoolSize(properties.getCorePoolSize());
		threadPoolTaskExecutor.setMaxPoolSize(properties.getMaxPoolSize());
		//线程空闲30s就会被回收, 避免推送事件的线程池占用太多线程
		threadPoolTaskExecutor.setKeepAliveSeconds(properties.getKeepAliveSeconds());
		//推送事件任务入队最多1000个 超过1000个在最大线程数范围内开启新线程处理新任务;超过最大线程数, 则执行拒绝策略
		threadPoolTaskExecutor.setQueueCapacity(properties.getQueueCapacity());
		//允许核心线程空闲时超时
		threadPoolTaskExecutor.setAllowCoreThreadTimeOut(true);
		threadPoolTaskExecutor.setThreadNamePrefix(THREAD_PREFIX_NAME_EVENT_DELIVER);
		return threadPoolTaskExecutor;
	}
}
